package com.studysystem.controller;

import com.studysystem.dto.TestResultDTO;
import com.studysystem.dto.TestSubmitRequest;
import com.studysystem.entity.*;
import com.studysystem.repository.*;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/test")
public class TestController {
    private final CourseTestRepository courseTestRepository;
    private final TestQuestionRepository testQuestionRepository;
    private final QuestionOptionRepository questionOptionRepository;
    private final TestAttemptRepository testAttemptRepository;
    private final TestAnswerRepository testAnswerRepository;
    private final UserRepository userRepository;

    public TestController(CourseTestRepository courseTestRepository, TestQuestionRepository testQuestionRepository, QuestionOptionRepository questionOptionRepository, TestAttemptRepository testAttemptRepository, TestAnswerRepository testAnswerRepository, UserRepository userRepository) {
        this.courseTestRepository = courseTestRepository;
        this.testQuestionRepository = testQuestionRepository;
        this.questionOptionRepository = questionOptionRepository;
        this.testAttemptRepository = testAttemptRepository;
        this.testAnswerRepository = testAnswerRepository;
        this.userRepository = userRepository;
    }

    // 获取课程测试题目
    @GetMapping("/{courseId}")
    public List<TestQuestion> getTestQuestions(@PathVariable Long courseId) {
        List<CourseTest> tests = courseTestRepository.findByCourseId(courseId);
        if (tests.isEmpty()) return Collections.emptyList();
        return tests.get(0).getQuestions().stream().collect(Collectors.toList());
    }

    // 提交测试答案并自动评分
    @PostMapping("/submit")
    public TestResultDTO submitTest(@AuthenticationPrincipal UserDetails userDetails, @RequestBody TestSubmitRequest request) {
        Optional<User> userOpt = userRepository.findByUsername(userDetails.getUsername());
        if (userOpt.isEmpty()) return null;
        User user = userOpt.get();
        CourseTest test = courseTestRepository.findById(request.getTestId()).orElse(null);
        if (test == null) return null;

        TestAttempt attempt = new TestAttempt();
        attempt.setUser(user);
        attempt.setTest(test);
        attempt.setStartedAt(LocalDateTime.now());
        attempt.setCompletedAt(LocalDateTime.now());
        attempt.setAnswers(new HashSet<>());

        int score = 0;
        List<TestResultDTO.QuestionResult> questionResults = new ArrayList<>();

        for (TestSubmitRequest.AnswerDTO answerDTO : request.getAnswers()) {
            TestQuestion question = testQuestionRepository.findById(answerDTO.getQuestionId()).orElse(null);
            if (question == null) continue;
            TestAnswer answer = new TestAnswer();
            answer.setAttempt(attempt);
            answer.setQuestion(question);
            answer.setAnswerText(answerDTO.getAnswerText());
            answer.setSelectedOption(answerDTO.getSelectedOptionId() != null ? questionOptionRepository.findById(answerDTO.getSelectedOptionId()).orElse(null) : null);

            boolean isCorrect = false;
            String correctAnswer = "";
            String explanation = "";
            if (question.getType() == TestQuestion.QuestionType.MULTIPLE_CHOICE || question.getType() == TestQuestion.QuestionType.TRUE_FALSE) {
                // 选择题
                QuestionOption correctOption = question.getOptions().stream().filter(QuestionOption::getIsCorrect).findFirst().orElse(null);
                if (correctOption != null) {
                    correctAnswer = correctOption.getOptionText();
                    isCorrect = answer.getSelectedOption() != null && Objects.equals(answer.getSelectedOption().getId(), correctOption.getId());
                }
            } else {
                // 简答题/主观题（这里只做简单字符串比对）
                correctAnswer = "参考答案";
                isCorrect = answer.getAnswerText() != null && answer.getAnswerText().trim().length() > 0;
            }
            answer.setIsCorrect(isCorrect);
            answer.setPointsEarned(isCorrect ? (question.getPoints() != null ? question.getPoints() : 1) : 0);
            score += answer.getPointsEarned() != null ? answer.getPointsEarned() : 0;
            testAnswerRepository.save(answer);
            attempt.getAnswers().add(answer);

            TestResultDTO.QuestionResult qr = new TestResultDTO.QuestionResult();
            qr.setQuestionId(question.getId());
            qr.setIsCorrect(isCorrect);
            qr.setUserAnswer(answer.getAnswerText() != null ? answer.getAnswerText() : (answer.getSelectedOption() != null ? answer.getSelectedOption().getOptionText() : ""));
            qr.setCorrectAnswer(correctAnswer);
            qr.setExplanation(explanation);
            questionResults.add(qr);
        }
        attempt.setScore(score);
        attempt.setIsPassed(score >= (test.getPassingScore() != null ? test.getPassingScore() : 0));
        testAttemptRepository.save(attempt);

        TestResultDTO result = new TestResultDTO();
        result.setScore(score);
        result.setIsPassed(attempt.getIsPassed());
        result.setQuestionResults(questionResults);
        return result;
    }

    // 获取测试历史记录/解析
    @GetMapping("/attempt/{attemptId}")
    public TestAttempt getAttempt(@PathVariable Long attemptId) {
        return testAttemptRepository.findById(attemptId).orElse(null);
    }
} 